<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class NotificationService {

    public static function get($take, $offset) {
        $cri = new CDbCriteria();
        $cri->limit = $take;
        $cri->offset = $offset;
        $cri->condition = 'NguoiDungId = ' . Yii::app()->user->id;
        return $Noti = VwNotification::model()->findAll($cri);
    }

    public static function markAsRead($Id) {
        return Notification::model()->updateByPk($Id, array('isRead' => 1));
    }

    public static function add($NguoiDungId, $Type, $Data) {
        if (count(Notification::model()->findAllByAttributes(array('NguoiDungId' => $NguoiDungId, 'NotificationType' => $Type, 'NotificationData' => $Data))) > 0) {
            return;
        }
        $Notify = new Notification();
        $Notify->NguoiDungId = $NguoiDungId;
        $Notify->NotificationType = $Type;
        $Notify->NotificationData = $Data;
        $Notify->timestamp = date('Y-m-d H:i:s');
        $Notify->save();
    }

    public static function PushNotifyForFollower($IdYTuong) {
        $YTuong = YTuong::model()->findByPk($IdYTuong);
        $danhmucs = $YTuong->getRelated('danhmucs');
        foreach ($danhmucs as $danhmuc) {
            $nguoidungs = $danhmuc->getRelated('nguoidungs');
            foreach ($nguoidungs as $nguoidung) {
                NotificationService::add($nguoidung->Id, 'NEW_IDEA', $IdYTuong);
            }
        }
        $followers = TheoDoiNguoiDung::model()->findAllByAttributes(array('NguoiDungId2' => Yii::app()->user->id));
        foreach ($followers as $follower) {
            NotificationService::add($follower->NguoiDungId1, 'NEW_IDEA', $IdYTuong);
        }
    }

    public static function PushFriendRequest($friendId) {
        $Noti = new Notification();
        $Noti->NguoiDungId = Yii::app()->user->Id;
        $Noti->NotificationType = 'FRIEND_REQUEST';
        $Noti->NotificationData = $friendId;
        $Noti->timestamp = date('Y-m-d');
        return $Noti->save();
    }

}
